

# 根据网上的腐蚀算法，自己写了一遍

import numpy as np
from random import sample, seed
# ~ seed(2)
seed(1)

plate = [0, 1, 2, 3]
plate = [0, 1]

def show(pic):
    def f(n):
        return " %#`"[n] * 2
    for line in pic:
        print(''.join(f(x) for x in line))

def gen(n_, base_):
    print("size", 2 **n_, "base", 2 ** base_, "grid", 2 ** (n_ - base_))
    pic = np.zeros((2**n_, 2**n_), dtype="int")
    n = 2 ** n_
    base = 2 ** base_
    grid = 2 **(n_ - base_)

    for j in range(grid):
        for i in range(grid):
            pic[i *base: (i + 1)*base, j *base: (j + 1)*base] = sample(plate, 1)

    for sbase_ in range(1, base_)[::-1]:
        sbase = 2 ** sbase_
        grid = 2 **(n_ - sbase_)
        print(sbase, grid)
        for j in range(grid):
            for i in range(grid):
                plate2 = []
                left = i *sbase
                right = (i+1) *sbase
                top = j *sbase
                bottom = (j + 1) * sbase

                if left > 0: plate2.append(pic[left-1, top])
                if right < n: plate2.append(pic[right, top])
                if top > 0: plate2.append(pic[left, top - 1])
                if bottom < n: plate2.append(pic[left, bottom])
                pic[i *sbase: (i + 1)*sbase, j *sbase: (j + 1)*sbase] = sample(plate2, 1)
    # ~ show(pic)
    return pic

# ~ r = gen(6, 4)
# ~ r = gen(7, 4)
# ~ r = gen(7, 5)
# ~ r = gen(8, 6)
# ~ r = gen(6, 3)
if __name__ == "__main__":
    r = gen(5, 2)
    xx = np.array([
    [255, 0, 0],
    [0, 200, 0],
    # ~ [0, 0, 255],
    # ~ [250, 150, 50],
    ], dtype="uint8")
    r = xx[r]
    from PIL import Image
    pic = Image.fromarray(r)
    x, y = pic.size
    # ~ pic = pic.resize((x * 4, y * 4), Image.Resampling.NEAREST )
    pic = pic.resize((x * 4, y * 4), Image.Resampling.NEAREST )
    pic.save("myg.png")









